其他
面试官:Spring 中的 Service 有多个实现类,怎么注入?
专属福利
public interface HumanService {
public String name();
}
@Service
public class TeacherServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("teacher");
return "teacher";
}
}
@Service
public class DoctorServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("doctor");
return "doctor";
}
}
@RestController
public class HumanController {
// @Resource(type = DoctorServiceImpl.class) //方法二
@Autowired
@Qualifier("teacherServiceImpl")
private HumanService humanService;
@RequestMapping("/name")
public String name(){
return humanService.name();
}
}
public interface HumanService {
public String name();
}
@Service("teacherService")
public class TeacherServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("teacher");
return "teacher";
}
}
@Service("doctorService")
public class DoctorServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("doctor");
return "doctor";
}
}
@RestController
public class HumanController {
@Resource(name="doctorService")
private HumanService humanService;
@RequestMapping("/name")
public String name(){
return humanService.name();
}
}
我就知道你会点赞+“在看”